package com.xxl.controller;


import com.xxl.util.FieldConst;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author xxl
 * @date 2023/3/14
 */
@Order(4000)
@Controller
@RequestMapping("user")
public class LoginController {
    @Resource
    HttpSession session;
    @Resource
    HttpServletRequest request;

    @PostMapping("login")
    public String login(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            @RequestParam(value = "isRemember",required = false) boolean isRemember,
            Model model
    )
    {
        try {
            //shiro登录
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            //登录成功 subject.getPrincipal()这个能取出信息主要还是看认证那边有没有存取信息
            session.setAttribute(FieldConst.USER_INFO,subject.getPrincipal());
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不正确");
            //没有此用户
            return "forward:/view/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码不正确");
            //密码不正确
            return "forward:/view/login";
        }
        return "redirect:/"+"?isRemember="+(isRemember ? "true":"false");
    }

    @GetMapping("logout")
    public String logout() {
        //shiro退出登录
        SecurityUtils.getSubject().logout();
        //清除session
        session.invalidate();
        //清除cookie
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(FieldConst.COOKIE_ID)) {
                cookie.setMaxAge(0);
            }
        }
        return "redirect:/view/login";
    }

}
